# from icecream import ic
import json
import os
import sys
from datetime import datetime

import pandas as pd
import requests

from get_sql_res import gen_run_detail, gen_data_cluster
from get_response import gen_wafermap_config_mapping, gen_wafermap_config
from gen_info_dic import gen_info_dic

directory_path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(directory_path, 'cfgs/mapping_char.json')

with open(file_path, 'r',encoding='utf8') as file:
    mapping_char = json.load(file)


def gen_MAP_one(df_run_detail, info_dic, lot_id, wafer_id):

    input_dict = info_dic['input_dict_for_mapping']
    output_dict = info_dic['output_dict_for_mapping']
    df_run_detail = df_run_detail[df_run_detail['wafer_id'] == wafer_id]
    lst = []
    for id in info_dic['input_virtual_ids']:
        df = {}
        df['Lot ID'] = lot_id
        df['Wafer ID'] = wafer_id
        df['Test Stage'] = info_dic['test_stage']
        if ',' in id:
            df['Output Data Source'] = mapping_char[output_dict[int(id.split(',')[0])]]
            df['Test Program'] = ''
            res = ''
            for i in id.split(','):
                res += input_dict[int(i)] + ','
            res = res[:-1]
            df['Input Virtual DataSet'] = res
            df['Output Virtual DataSet'] = input_dict[int(id.split(',')[0])]
        else:
            df['Output Data Source'] = mapping_char[output_dict[int(id)]]
            df['Test Program'] = ''
            df['Input Virtual DataSet'] = input_dict[int(id)]
            df['Output Virtual DataSet'] = input_dict[int(id)]

        lst.append(df)
    res_df = pd.DataFrame(lst)
    for rule_name in info_dic['rule_map'].keys():
        # 空着，用来放图片
        res_df[rule_name] = ''

    return res_df


def gen_MAP(df_run_detail, info_dic):
    lst_MAP = []
    lot_wafer_id = info_dic['lot_wafer_id']
    for lot_id in lot_wafer_id.keys():
        for wafer_id in lot_wafer_id[lot_id]:

            # MAP
            MAP_one = gen_MAP_one(df_run_detail, info_dic, lot_id, wafer_id)
            lst_MAP.append(MAP_one)
    # MAP
    MAP_df = pd.concat(lst_MAP, ignore_index=True)
    info_dic['df_info']['MAP']={
        'col_num':len(MAP_df.columns),
        'row_num':len(MAP_df)+1
    }
    for i,rule_name in enumerate(info_dic['rule_map'].keys()):
        info_dic['df_info']['MAP'][rule_name]=7+i+1
    # print(info_dic['df_info']['MAP'])
    return MAP_df


if __name__ == '__main__':
    input = sys.argv[1]
    input = json.loads(input)
    rule_run_record_id = input['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = input['mysqlInfo']
    sql_info['ckInfo'] = input['ckInfo']
    sql_info['dasHost'] = input['dasHost']
    re_file_path = input['fileFullPath']
    current_time = datetime.now().strftime("%m_%d_%H_%M")
    re_file_path = f"/home/tom/codes/A8_v2/res/file_{current_time}.xlsx"

    df_run_detail = gen_run_detail(rule_run_record_id,sql_info)
    info_dic=gen_info_dic(df_run_detail,sql_info)

    wafer_id='NT41A_06'
    ##
    gen_MAP(df_run_detail, info_dic)
